<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>vue2的事件总线</h2>
      <child1></child1>
      <child2></child2>
    </div>

    <script src="./lib/Vue2.js"></script>
    <script>
      // 创建一个额外的父组件
      const bus = new Vue();

      const Child1 = {
        data() {
          return {
            count: 10,
          };
        },
        template: `
          <div>child子组件1 - <button @click="fn">btn</button></div>
        `,
        methods: {
          fn() {
            bus.$emit("change", this.count);
          },
        },
      };

      const Child2 = {
        data() {
          return {
            num: null,
          };
        },
        template: `
          <div>child子组件2 - {{ num }}</div>
        `,
        mounted() {
          // 用于做事件监听,开启监听
          bus.$on("change", (val) => {
            console.log(val);
            this.num = val;
          });
        },
        beforeDestroy() {
          // 关闭监听
          bus.$off("change");
        },
      };

      new Vue({
        el: "#app",
        data: {},
        components: {
          Child1,
          Child2,
        },
      });
    </script>
  </body>
  <html></html>
</html>
